package com.example.mychat.Controller;

import com.alibaba.fastjson.JSONObject;
import com.example.mychat.Service.wsService;
import com.example.mychat.Utils.UserSessionRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class WebSocketConnection extends AbstractWebSocketHandler {

    @Autowired
    private UserSessionRegistry userSessionRegistry;
    @Autowired
    private wsService wservice;

    private static WebSocketSession session;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
//        //这一步是获取前端在连接时传递的会话属性——id
//        Object myUserId = session.getAttributes().get("userId");
//        //存进用户信息缓存中
//        userSessionRegistry.registerSession(myUserId.toString(),session.toString());

        // 获取握手请求的头部信息
        String userId = session.getUri().getQuery().split("&")[0].split("=")[1];
        log.info("连接已建立");
        log.info(userId);
        log.info(session.getId());
        userSessionRegistry.registerSession(userId.toString(), session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String payload = (String)message.getPayload();
        Boolean type=getHertpackage(payload);
        if(type==false){
            log.info("收到消息：" + payload);
            // 向客户端发送响应消息
            String[] mesPart = message.getPayload().toString().split(":");
//        消息接收者id
            String toId = mesPart[0];
            //聊天id
            String chatid=mesPart[1];
//        消息体
            String mes = mesPart[2].split(";")[1];
//        消息发送者id
            String sendId = mesPart[2].split(";")[0];
//        最终消息结构
            String toMes = sendId + ":" + chatid + ":" + mes;

//            userSessionRegistry.getSessionId(toId).sendMessage(new TextMessage(toMes));

            WebSocketSession webSocketSession=userSessionRegistry.getSessionId(toId);
            if(webSocketSession!=null && webSocketSession.isOpen()){
                webSocketSession.sendMessage(new TextMessage(toMes));
                wservice.handleMes(chatid,toMes);
            }else{
                log.info("对方为离线状态");
                wservice.handleMes(chatid,toMes);
            }
        }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("连接已关闭！");
        this.session = null;
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public Boolean getHertpackage(String s) {
        Boolean result = false;
        try {
            JSONObject jsonObject=JSONObject.parseObject(s);
            String type=jsonObject.getString("type");
            if("ping".equals(type)){
                log.info("收到心跳包");
                result=true;
            }else{
                result=false;
            }
        }catch(Exception e){
            log.info(e.toString());
        }
        return result;
    }
}
